package top.zackyoung.mq.rocketmq.demo.transaction;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @version 1.0
 * @description:
 * @author: ZackYoung
 * @date: 2021/4/3 17:49
 */
@Service
@Slf4j
public class OrderService {
    @Resource
    RocketMQTemplate rocketMQTemplate;

    public void createOrderBefore(Order order) {
        String txId = UUID.randomUUID().toString();
        // 发送事务消息
        rocketMQTemplate.sendMessageInTransaction(
                "tx-producer-group", "tx-topic",
                MessageBuilder.withPayload(order).setHeader("txId", txId).build(), order);
    }

    @Transactional(rollbackFor = Exception.class)
    public void createOrder(Order order, String txId) {
        log.info("我创建了一个 [{txId}] 的订单", txId);
    }
}
